/**
 * 抖音直播数据弹窗模组
 * 处理直播数据记录和显示
 */
import cssText from "data-text:~/assets/css/data_screen.css"
import antdResetCssText from "data-text:antd/dist/reset.css"
import type {
  PlasmoCSConfig,
  PlasmoGetRootContainer,
  PlasmoGetShadowHostId
} from "plasmo"
import React, { useEffect, useState } from "react"

import { usePort } from "@plasmohq/messaging/hook"

import DataRecordModalIndex from "~ui_components/DataRecordModalIndex"

// 注入配置
export const config: PlasmoCSConfig = {
  matches: [
    // 抖音直播数据大屏(专业版)
    "https://compass.jinritemai.com/screen/live/*"
  ],
  run_at: "document_end",
  all_frames: true
}

// 注入的shadow dom的id
export const HOST_ID = "data-record-modal"
export const getShadowHostId: PlasmoGetShadowHostId = () => HOST_ID

/**
 * 自定义根容器
 * 挂载到body下, 阻止弹窗内的滚动事件冒泡
 */
export const getRootContainer: PlasmoGetRootContainer = () => {
  const rootContainer = document.createElement("div")
  const shadowHost = document.createElement("div")
  rootContainer.id = HOST_ID
  shadowHost.appendChild(getStyle())
  shadowHost.appendChild(rootContainer)
  document.body.insertAdjacentElement("beforeend", shadowHost)
  return rootContainer
}

// 注入样式
export const getStyle = () => {
  const style = document.createElement("style")
  style.textContent = cssText + antdResetCssText
  return style
}

const DyDataRecordModal: React.FC = () => {
  // 直播大屏数据port
  const dyLiveScreenData = usePort("dyLiveScreenData")

  // hijackEvent事件响应方法
  const eventHandler = (
    event: CustomEvent<{
      url: string
      response: any
    }>
  ) => {
    dyLiveScreenData.send(event.detail)
  }

  useEffect(() => {
    dyLiveScreenData.send({ action: "init" })
    // 监听数据
    window.addEventListener("hijackEvent", eventHandler)
    // 卸载监听
    return () => {
      window.removeEventListener("hijackEvent", eventHandler)
    }
  }, [])

  return (
    <DataRecordModalIndex HostId={HOST_ID} hijackData={dyLiveScreenData.data} />
  )
}

export default DyDataRecordModal
